var Md5 = require('../utils/md5.js');
const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
};
const formatData = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()

    return [year, month, day].map(formatNumber).join('-')
};

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}
function http(url, data, callback) {
    data.key = wx.getStorageSync("key");
    data.timestamp = Date.parse(new Date()) / 1000;
    var sign = Md5.hexMD5(data.timestamp + 'iqidian' + data.key); //md5加密
    data.sign = sign;
    wx.request({
        url: url,
        data: data,
        header: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        dataType: "json",
        success: function(res) {
            callback(res.data)
        },
        fail: function(res) {},
        complete: function(res) {},
    })
};

function message(msg) {
    wx.showModal({
        title: '温馨提示',
        content: msg,
        showCancel: false,
        success(res) {}
    })
}
function showLoading(msg) {
    wx.showLoading({
        mask:true,
        title: msg ? msg : '加载中',
    })
}
function hideLoading() {
    wx.hideLoading();
}
// getPastTime:判断发布过去时间间隔
function getPastTime(time) {
    // time为传入的时间戳        
    let date = new Date();
    let time1 = date.getTime();
    let time2 = (time1 - time) / 1000;
    let pastTimes = '';
    if (time2 < 300) {
        pastTimes = '刚刚';
    } else if (time2 >= 300 && time2 < 1800) {
        pastTimes = '5分钟前';
    } else if (time2 >= 1800 && time2 < 3600) {
        pastTimes = '30分钟前';
    } else if (time2 >= 3600 && time2 < 86400) {
        pastTimes = '1小时前';
    } else if (time2 >= 86400 && time2 < 259200) {
        pastTimes = '一天前';
    } else if (time2 >= 259200) {
        let date3 = new Date(time);
        pastTimes = date3.getFullYear() + '-' + (date3.getMonth() + 1) + '-' + date3.getDate();
    }
    return pastTimes;
}

module.exports = {
    formatTime: formatTime,
    http: http,
    formatData: formatData,
    message: message,
    getPastTime: getPastTime,
    showLoading: showLoading,
    hideLoading: hideLoading
}